﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.IO;
using System.Net;
using Model;

namespace Web
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
        }

        void Application_End(object sender, EventArgs e)
        {
            //  在应用程序关闭时运行的代码

        }

        void Application_Error(object sender, EventArgs e)
        {
            // 在出现未处理的错误时运行的代码

        }

        void Session_Start(object sender, EventArgs e)
        {
            // 在新会话启动时运行的代码
        }

        void Session_End(object sender, EventArgs e)
        {
            // 在会话结束时运行的代码。 
            // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
            // InProc 时，才会引发 Session_End 事件。如果会话模式设置为 StateServer 
            // 或 SQLServer，则不会引发该事件。

        }

        void Application_BeginRequest(object sender, EventArgs e)
        {
            bool moveFlag = false;

            //URL重写时首页index.aspx转换无效,放在这里处理
            string curPath = System.Web.HttpContext.Current.Request.RawUrl;
            if (curPath.ToLower().Equals("/index.aspx"))
            {
                curPath = "/";
                //moveFlag = true;
            }

            //替换所有没加www的域名
            if (System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToLower().Equals("itkaifa.com"))
                moveFlag = true;

            if (moveFlag)
            {
                string newurl = BaseCode.CommValue.Domain + curPath;
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.StatusCode = 301;
                System.Web.HttpContext.Current.Response.Status = "301 Moved Permanently";
                System.Web.HttpContext.Current.Response.AddHeader("Location", newurl);
            }
        }

        void AddTimerCache()
        {
            if (BaseCode.CacheProvider.GetCache("TimerCache") == null)
            {
                System.Web.Caching.CacheItemRemovedCallback onRemove = new System.Web.Caching.CacheItemRemovedCallback(RemovedCallback);
                BaseCode.CacheProvider.SetCache("TimerCache", "",
                    System.DateTime.Now.AddMinutes(1),
                    System.Web.Caching.Cache.NoSlidingExpiration,
                    System.Web.Caching.CacheItemPriority.High,
                    onRemove);
            }
        }

        void RemovedCallback(String k, Object v, System.Web.Caching.CacheItemRemovedReason r)
        {
            Common.FileHelper.AppendFile(string.Format("{0}\r\n", System.DateTime.Now.ToString()), string.Format("{0}log.txt", System.AppDomain.CurrentDomain.BaseDirectory));
            AddTimerCache();
        }
    }
}
